package com.info.zhiduoduo.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.exception.SmartException;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.HttpUtil;
import com.info.zhiduoduo.common.utils.IPUtil;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.common.utils.NumberUtil;
import com.info.zhiduoduo.common.utils.RandomUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.formbean.ExamineNoticeFormBean;
import com.info.zhiduoduo.core.formbean.NoticeFormBean;
import com.info.zhiduoduo.core.formbean.mqproducer.PhoneMessage;
import com.info.zhiduoduo.core.formbean.mqproducer.Producer;
import com.info.zhiduoduo.core.service.CommonService;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.util.SmsUtil;
import com.info.zhiduoduo.repository.entity.system.PhoneCode;

import com.info.zhiduoduo.repository.entity.system.SystemCfg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class CommonServiceImpl extends BaseService implements CommonService {

	@Autowired
	Producer producer;

	@Autowired
	ZddUrlConfig zddUrlConfig;

	@Override
	public SmartResult sendPhoneVerifyCode(HttpServletRequest httpServletRequest, String phone) {
		String verifyCode = RandomUtil.getRandomNum(4);

		PhoneCode phoneCode = new PhoneCode().selectById(phone);
		if(null == phoneCode){
			phoneCode= new PhoneCode();
			phoneCode.setIpaddr(IPUtil.getIpAddr(httpServletRequest));
			phoneCode.setPhone(phone);
			phoneCode.setVerifycode(verifyCode);
			phoneCode.setState(1);
			phoneCode.insert();

		}else{
			//是否超过 60 秒
			if(DateUtil.getNumsByAppointedTimestamp(phoneCode.getCreatetime(),2)<=60){
				return SmartResult.fail(StatusMsg.StatusMsg_107);
			}else{
				phoneCode.setVerifycode(verifyCode);
				phoneCode.setCreatetime(DateUtil.getNowTimestamp());
				phoneCode.setState(1);
				phoneCode.updateById();
			}
		}

		PhoneMessage phoneMessage = new PhoneMessage();
		phoneMessage.setPhone(phone);
		phoneMessage.setVerifycode(verifyCode);
		phoneMessage.setType(1);
		try {
			SmsUtil.send(phoneMessage);
		} catch (ClientException e) {
			log.error("短信发送失败:", e);
		} catch (InterruptedException e) {
			log.error("短信发送失败:", e);
		} catch (Exception e) {
			log.error("短信发送失败:", e);
		}
//		producer.sendSms(phoneMessage);

		return SmartResult.success();
	}

	@Override
	public void sendBirthSms(String phone) {
		JSONObject object = new JSONObject();
		object.put("phone", phone);
		producer.sendMq("Zdd_BirthSmsQueue", object.toJSONString());
	}

	@Override
	public void sendAnniversarySms(String phone, String year) {
		JSONObject object = new JSONObject();
		object.put("phone", phone);
		object.put("year", year);
		producer.sendMq("Zdd_AnniversarySmsQueue", object.toJSONString());
	}

	@Override
	public void checkPhoneVerifyCode(String phone, String verifyCode) {
		// 验证码
		PhoneCode phoneCode = new PhoneCode().selectById(phone);
		// 不存在手机号码
		Asserts.notNull(phoneCode, StatusMsg.StatusMsg_104);
		// 验证码错误
		Asserts.isTrue(StringUtil.equals(verifyCode, phoneCode.getVerifycode()), StatusMsg.StatusMsg_106);
		// 是否已经使用过了
		Asserts.isTrue(!NumberUtil.equals(phoneCode.getState(), 2), StatusMsg.StatusMsg_140);
		// 是否超过 10 分钟
		if (DateUtil.getNumsByAppointedTimestamp(phoneCode.getCreatetime(), 1) > 10) {
			phoneCode.setState(3).updateById();
			throw new SmartException(StatusMsg.StatusMsg_112);
		}

		// 如果有效，将验证码标记为已使用
		phoneCode.setState(2).updateById();
	}

	@Override
	public SmartResult sendEnterpriseWeChatNotice(int businessManagerId, String name, int type) {

		BaseSimpleFormBean formBean = new BaseSimpleFormBean();
		ExamineNoticeFormBean bean = new ExamineNoticeFormBean();
		bean.setId(businessManagerId);
		bean.setName(name);
		bean.setType(type);
		formBean.setReqdata(bean);
		LogUtil.info("sendEnterpriseWeChatNotice 开始请求---");
		try {
			RestTemplate rest = new RestTemplate();
//			return rest.postForObject(zddUrlConfig.getBaseCRMUrl() + "/weChat/examineNotice", formBean, SmartResult.class);
			return null;
		} catch (RestClientException e) {
			log.error("调用crm,发送企业微信消息给商务经理报错:{}", JSON.toJSONString(bean), e);
		}

		LogUtil.info("请求失败---");
		return SmartResult.fail();
	}

	@Override
	public SmartResult enterpriseAutomaticFreezing(int businessManagerId, String name) {

		BaseSimpleFormBean formBean = new BaseSimpleFormBean();
		ExamineNoticeFormBean bean = new ExamineNoticeFormBean();
		bean.setId(businessManagerId);
		bean.setName(name);
		bean.setType(0);
		formBean.setReqdata(bean);
		LogUtil.info("sendEnterpriseWeChatNotice 开始请求---");
		try {
			RestTemplate rest = new RestTemplate();
//			return rest.postForObject(zddUrlConfig.getBaseCRMUrl() + "/weChat/freezeNotice", formBean, SmartResult.class);
			return null;
		} catch (RestClientException e) {
			log.error("调用crm,发送企业微信消息给商务经理报错:{}", JSON.toJSONString(bean), e);
		}

		LogUtil.info("请求失败---");
		return SmartResult.fail();
	}

	@Override
	public SmartResult sendEnterpriseWeChatNotice(int businessManagerId, String name, int type, String info) {
		BaseSimpleFormBean formBean = new BaseSimpleFormBean();
		NoticeFormBean bean = new NoticeFormBean();
		bean.setId(businessManagerId);
		bean.setName(name);
		bean.setType(type);
		bean.setInfo(info);

		formBean.setReqdata(bean);
		log.info("sendEnterpriseWeChatNotice 开始请求---businessManagerId:{}, info = {}", businessManagerId, info);
		try {
			RestTemplate rest = new RestTemplate();
//			return rest.postForObject(zddUrlConfig.getBaseCRMUrl() + "/weChat/notice", formBean, SmartResult.class);
			return null;
		} catch (RestClientException e) {
			log.error("调用crm,发送企业微信消息给商务经理报错:{}", JSON.toJSONString(bean), e);
		}

		LogUtil.info("请求失败---");
		return SmartResult.fail();
	}

	@Override
	public SmartResult validateCardInfo(String cardNo) {
		String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?cardBinCheck=true&cardNo=" + cardNo;
		try {
			String json = HttpUtil.get(url, null);
			JSONObject obj = JSON.parseObject(json);
			return SmartResult.success(obj);
		} catch (Exception e) {
			log.info("验证银行卡失败:", e);
		}
		return SmartResult.fail();
	}

	@Override
	public void validRestraintTradeTime(Date time) {
		//开始时间 eg: 06:00
		SystemCfg start = new SystemCfg().selectById(Constants.RESTRAINT_TRADE_START);
		//结束时间 eg: 18:00
		SystemCfg end = new SystemCfg().selectById(Constants.RESTRAINT_TRADE_END);
		if (start != null && end != null) {
			//当前时间
			SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.FORMAT_STYLE_14);
			String checkTime = sdf.format(time);
			boolean isRestraint = DateUtil.isInTimeRange(checkTime, start.getCfgValue(), end.getCfgValue());
			String msg = "企业" + start.getCfgValue() + "-" + end.getCfgValue() + "不能验收项目成果并支付，请在除此以外的时间进行验收。";
			if(isRestraint) {
				throw new SmartException(StatusMsg.StatusMsg_146.state, msg);
			}
		}
	}

}
